package com.dwxt.mall.service;

import com.dwxt.common.base.BaseResult;
import com.dwxt.common.util.JsonUtils;
import com.dwxt.mall.dao.TrainHallMapper;
import com.dwxt.mall.entity.Product;
import com.dwxt.mall.entity.TrainHall;
import com.dwxt.mall.entity.TrainHallExample;
import com.dwxt.mall.entity.vo.TrainHallVO;
import com.github.pagehelper.PageInfo;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class TrainHallService {

    @Autowired
    private TrainHallMapper trainHallMapper;

    @Autowired
    private ProductService productService;

    public BaseResult selectHallList(TrainHall hall) {
        GlobalCoordinates source = new GlobalCoordinates(Double.parseDouble(hall.getLatitude()),
                Double.parseDouble(hall.getLongitude()));
        TrainHallExample example = new TrainHallExample();
        example.setOrderByClause("priority desc,create_time asc");
        List<TrainHall> trainHalls = trainHallMapper.selectByExampleWithBLOBs(example);
        PageInfo<TrainHall> pageInfo = new PageInfo<>(trainHalls);
        List<TrainHall> trainHallVOS = trainHalls.stream().map(trainHall -> {
            GlobalCoordinates target = new GlobalCoordinates(Double.parseDouble(trainHall.getLatitude()),
                    Double.parseDouble(trainHall.getLongitude()));
            GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.Sphere, source, target);
            TrainHallVO trainHallVO = JsonUtils.jsonToPojo(JsonUtils.objectToJson(trainHall), TrainHallVO.class);
            trainHallVO.setMeter(geoCurve.getEllipsoidalDistance());
            return trainHallVO;
        }).collect(Collectors.toList());
        pageInfo.setList(trainHallVOS);
        return BaseResult.ok(pageInfo);
    }

    public List<Product> selectProductById(Integer id) {
        return productService.selectProductBySupplierId(id);
    }
}
